package middleware

import (
	"editor/constant"
	"editor/utils"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

func CheckIsLogin() gin.HandlerFunc {
	return func(c *gin.Context) {

		if utils.GetSession(c, constant.UserName) != constant.Config.Login.User {
			accept := c.Request.Header.Get("Accept")
			if strings.Index(accept, "html") > -1 {
				c.Abort()
				c.Redirect(http.StatusFound, "/login")
			} else {
				c.AbortWithStatusJSON(http.StatusOK, constant.Response{
					Code: -1,
					Msg:  "no login",
					Data: nil,
				})
			}
			return
		} else {
			utils.SetSession(c, constant.UserName, constant.Config.Login.User, 3600)
		}

		c.Next()
		return
	}
}
